<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene"></Category>
    <el-card style="margin: 10px 0;">
      <!-- v-show:只需要挂载一次，就可以隐藏/显示 v-if:销毁并创建组件 消耗系统性能-->
      <div v-show="scene==0">
        <el-button @click="addSPU" type="primary" icon="Plus" :disabled="categoryStore.c3Id?false:true">添加SPU</el-button>
        <el-table :data="records" style="margin: 10px 0;" border>
          <el-table-column label="序号" type="index" align="center" width="100px"></el-table-column>
          <el-table-column label="SPU名称" prop="spuName"></el-table-column>
          <el-table-column label="SPU描述" prop="description" show-overflow-tooltip></el-table-column>
          <el-table-column label="SPU操作">
            <template #="{row}">
              <el-button @click="addSKU(row)" type="primary" size="small" icon="Plus" title="添加SKU"></el-button>
              <el-button @click="updateSPU(row)" type="warning" size="small" icon="Edit" title="修改SPU"></el-button>
              <el-button @click="findSku(row)" type="success" size="small" icon="View" title="查看SKU列表"></el-button>
              <el-popconfirm :title="`确认删除${row.spuName}吗？`" width="200" @confirm="deleteSpu(row)">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" title="删除SPU"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes, total"
          :total="total"
          @current-change="getHasSpu"
          @size-change="sizeChange"
        />
      </div>
      <!-- 添加|修改SPU 子组件 -->
      <SpuForm ref="SpuFormRef" v-show="scene==1" @changeScene="changeScene"></SpuForm>
      <!-- 添加SKU子组件 -->
      <SkuForm ref="SkuFormRef" v-show="scene==2" @changeScene="changeScene"></SkuForm>
      <!-- sku列表对话框 -->
      <el-dialog v-model="show" title="SKU列表">
        <el-table border :data="skuArr">
          <el-table-column label="SKU名字" prop="skuName"></el-table-column>
          <el-table-column label="SKU价格" prop="price"></el-table-column>
          <el-table-column label="SKU重量" prop="weight"></el-table-column>
          <el-table-column label="SKU图片">
            <template #="{row}">
              <img :src="row.skuDefaultImg" style="width: 100px;height: 100px;"/>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref,watch,onBeforeUnmount } from 'vue';
import useCategoryStore from '@/store/modules/category';
import { reqHasSpu,reqSkuList,reqRemoveSpu } from '@/api/product/spu';
import type { HasSpuResponseData,Records,SpuData,SkuInfoData,SkuData } from '@/api/product/spu/type';
import SpuForm from './spuForm.vue'
import SkuForm from './skuForm.vue'
import { ElMessage } from 'element-plus';
let categoryStore = useCategoryStore()
let scene = ref<number>(0) //0显示SPU列表 1添加|修改SPU 2添加SKU
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let records = ref<Records>([])
// 获取SpuForm子组件实例
let SpuFormRef = ref<any>()
// 获取SkuForm子组件实例
let SkuFormRef =  ref<any>()
// 存储全部sku列表数据
let skuArr = ref<SkuData[]>([])
let show = ref<boolean>(false)
// 监听三级分类id
watch(() => categoryStore.c3Id,()=> {
  if(!categoryStore.c3Id) return
  getHasSpu()
})
// 获取某个三级分类下列表数据
const getHasSpu = async(pager=1)=> {
  pageNo.value = pager //修改当前页码，默认查询第一页
  let result:HasSpuResponseData = await reqHasSpu(pageNo.value,pageSize.value,categoryStore.c3Id)
  if(result.code==200){
    records.value = result.data.records
    total.value = result.data.total
  }
}
const sizeChange = ()=> {
  getHasSpu()
}
// 添加SPU
const addSPU = ()=> {
  // 切换场景1：添加/修改已有spu结构 -> spuForm
  scene.value = 1
  // 点击添加spu按钮，调用子组件方法 初始化数据
  SpuFormRef.value.initAddSpu(categoryStore.c3Id) //传递三级id
}
// 修改SPU
const updateSPU = (row:SpuData)=> {
  scene.value = 1
  // 父组件点击修改按钮时，获取子组件的vc实例，调用initHasSpuData()方法发送请求
  // 如果使用v-if：最开始模板中没有子组件实例，点击修改按钮，响应式数据scene发生变化，模板更新，获取更新后的dom需要使用nextTick()
  // 但是使用v-show：最初的模板已经有了子组件，只是被隐藏了，所以可以拿到子组件的实例SpuFormRef.value
  // console.log(SpuFormRef.value);
  SpuFormRef.value.initHasSpuData(row) //每次点击修改按钮就会调用子组件方法
  
}
// 子组件SPUfrom绑定的自定义事件：让子组件通知父组件场景切换为0
const changeScene = (obj:any)=>{
  // 子组件SPUform点击取消变为场景0：展示SPU列表
  scene.value = obj.flag
  // 刷新数据
  getHasSpu()
  if(obj.params=='update'){
    // 更新留在当前页
    getHasSpu(pageNo.value)
  }else{
    // 添加留在第一页
    getHasSpu()
  }
}
// 添加SKU
const addSKU = (row:SpuData)=> {
  // 点击添加SKU按钮，切换场景为2
  scene.value = 2
  // 调用子组件的方法初始化添加SKU的数据
  SkuFormRef.value.initSkuData(categoryStore.c1Id,categoryStore.c2Id,row)
}
// 查看SKU列表
const findSku = async(row:SpuData)=> {
  let res:SkuInfoData = await reqSkuList((row.id as number))
  if(res.code==200){
    skuArr.value = res.data
    show.value = true
  }
}
// 删除SPU
const deleteSpu = async(row:SpuData)=> {
  let res = await reqRemoveSpu((row.id as number))
  if(res.code==200){
    ElMessage.success('删除成功！')
    // 刷新数据
    getHasSpu(records.value.length>1?pageNo.value:pageNo.value-1)
  }else{
    ElMessage.error('删除失败！')
  }
}
// 路由组件销毁前清空仓库关于分类数据
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped lang="scss">

</style>

<!-- 面试
  Q：在父组件内部如何拿到子组件的实例vc？如何拿到子组件的方法或属性？
    ref
-->
